export default {
	namespaced: true,
	// state: {
	// 	// 用来存储购物车每个商品的对象
	// 	// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
	// 	cart: []
	// },
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		addToCart(state,goods) {
			const findReault = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findReault) {
				findReault.goods_count ++
			}else {
				state.cart.push(goods)
			}
			console.log('store中cart',state.cart)
			this.commit('my_cart/saveCartToStorage')
		},
		// 本地存储购物车中数据
		saveCartToStorage(state) {
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		updateGoodsState(state,goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_state = goods.goods_state
			}
			this.commit('my_cart/saveCartToStorage')
		},
		updateGoodsCount(state,goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_count = goods.goods_count
			}
		},
		removeGoods(state,goods) {
			state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
			this.commit('my_cart/saveCartToStorage')
		},
		// 点击全选
		updateAllGoodsState(state,allGoodsState) {
			state.cart.forEach(item => {
				item.goods_state = allGoodsState
			})
			// 持久存储状态
			this.commit('my_cart/saveCartToStorage')
		}
	},
	actions: {
		
	},
	getters: {
		total(state) {
			let count = 0
			state.cart.forEach(item => count += Number(item.goods_count))
			return count
		},
		// 已勾选数量
		checkedCount(state) {
			return state.cart.filter(e => e.goods_state).reduce((total,item) => {
				return total += Number(item.goods_count)
			},0)
		},
		checkedTotalPrice(state) {
			return state.cart.filter(e => e.goods_state).reduce((total,item) => {
				return total += item.goods_price * item.goods_count
			},0).toFixed(2)
		}
	}
}